#include "MQ2Sensor.h"
#include "Config.h"

MQ2Sensor::MQ2Sensor(int aoPin, int doPin) 
    : _aoPin(aoPin), _doPin(doPin), _concentration(0), 
      _alert(false), _preheated(false), _startTime(0) {}

void MQ2Sensor::begin() {
    pinMode(_doPin, INPUT);
    _startTime = millis();
    Serial.println("MQ2传感器初始化完成，需要30秒预热");
}

void MQ2Sensor::update() {
    // 检查预热状态
    if(!_preheated) {
        if(millis() - _startTime >= PREHEAT_TIME) {
            _preheated = true;
            Serial.println("MQ2传感器预热完成");
        }
        return;
    }
    
    // 读取模拟值并计算PPM
    int sensorValue = analogRead(_aoPin);
    float voltage = sensorValue * (3.3 / 4095.0);
    float RS_gas = (5.0 - voltage) / voltage;
    float ratio = RS_gas / 9.8f; // 使用校准值
    _concentration = 1000.0f * pow(ratio, -2.95f);
    
    // 检查是否超过阈值
    _alert = (_concentration > SMOKE_THRESHOLD) || (digitalRead(_doPin) == LOW);
}

float MQ2Sensor::getConcentration() const {
    return _preheated ? _concentration : 0.0f;
}

bool MQ2Sensor::isAlert() const {
    return _preheated && _alert;
}

bool MQ2Sensor::isPreheated() const {
    return _preheated;
}
